package org.example.dao;

import org.example.entity.chatmessages;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DBUtil {

    private static final String url = "jdbc:mysql://localhost:3306/joydb";
    private static final String username = "root";
    private static final String password = "wanziyuan704";
    private static final int INITIAL_POOL_SIZE = 5; // 初始连接池大小
    private static final int MAX_POOL_SIZE = 20;    // 最大连接池大小

    private static List<Connection> connectionPool = new ArrayList<>();
    private static int checkedOut = 0;

    // 初始化连接池
    public DBUtil() {
        // 显式加载 MySQL 驱动程序
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(ex);
        }
        try {
            for (int i = 0; i < INITIAL_POOL_SIZE; i++) {
                Connection conn = DriverManager.getConnection(url, username, password);
                connectionPool.add(conn);
            }
            System.out.println("Connection pool initialized successfully."); // 添加日志
        } catch (SQLException e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError(e);
        }
    }

    public List<chatmessages> getUsers() {
        List<chatmessages> userList = new ArrayList<>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = getConn();
            String sql = "SELECT sender_id, receiver_id, message_content FROM chat_record"; // 使用正确的字段名
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                int sender = rs.getInt("sender_id"); // 使用正确的字段名
                int receiver = rs.getInt("receiver_id"); // 使用正确的字段名
                String message_content = rs.getString("message_content");
                chatmessages user = new chatmessages(sender, receiver, message_content);
                userList.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeConn(conn, ps, rs);
        }
        return userList;
    }

    // 获取数据库连接
    public static synchronized Connection getConn() throws SQLException {
        if (!connectionPool.isEmpty()) {
            int lastIdx = connectionPool.size() - 1;
            Connection conn = connectionPool.remove(lastIdx);
            if (conn.isValid(1)) {
                checkedOut++;
                return conn;
            }
        }
        if (checkedOut < MAX_POOL_SIZE) {
            Connection conn = DriverManager.getConnection(url, username, password);
            checkedOut++;
            return conn;
        }
        throw new SQLException("数据库连接已达到最大数量");
    }

    // 关闭数据库连接
    public synchronized void closeConn(Connection conn, PreparedStatement ps, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            connectionPool.add(conn);
            checkedOut--;
        }
    }

    public static int executePreparedUpdate(String sql, Object... params) {
        try (Connection conn = DriverManager.getConnection(url, username, password);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            // 设置参数
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i + 1, params[i]);
            }

            // 执行更新操作
            return pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            return -1; // 返回负数表示更新失败
        }
    }
}
